﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

TMX Tiled Map support:
	http://www.mapeditor.org
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;

namespace PKEngine
{
	/// <summary>
	/// PKTmxLayer represents the TMX layer.
	/// </summary>
	public class PKTmxLayer : PKNode
	{
		#region Private Fields
		private int maxGId;
		private int minGId;
		private int opacity;
		#endregion

		#region Public Properties
		/// <summary>
		/// Properties for the layer. They can be added using Tiled.
		/// </summary>
		public Dictionary<string, string> Properties { get; private set; }

		/// <summary>
		/// Tileset surface for the layer.
		/// </summary>
		public PKSurface Surface { get; private set; }

		/// <summary>
		/// Name of the layer.
		/// </summary>
		public string LayerName { get; set; }

		/// <summary>
		/// Size of the layer in tiles.
		/// </summary>
		public Size LayerSize { get; set; }

		/// <summary>
		/// Size of the map's tile. (could be differnt from the tile's size)
		/// </summary>
		public Size MapTileSize { get; set; }

		/// <summary>
		/// Array for the map of tiles.
		/// </summary>
		public int[] Tiles { get; set; }

		/// <summary>
		/// Tileset information for the layer.
		/// </summary>
		public PKTmxTilesetInfo Tileset { get; set; }
		#endregion

		#region Initialization
		public PKTmxLayer(PKTmxTilesetInfo tilesetInfo, PKTmxLayerInfo layerInfo, PKTmxMapInfo mapInfo)
			: base()
		{
			this.Surface = PKSurfaceCache.SharedSurfaceCache.AddImage(tilesetInfo.SourceImage);

			this.LayerName = layerInfo.Name;
			this.LayerSize = layerInfo.LayerSize;
			this.Tiles = layerInfo.Tiles;
			this.minGId = layerInfo.MinGId;
			this.maxGId = layerInfo.MaxGId;
			this.opacity = layerInfo.Opacity;
			this.Properties = layerInfo.Properties;

			this.Tileset = tilesetInfo;

			this.MapTileSize = mapInfo.TileSize;

			this.Position = this.PositionAt(layerInfo.Offset);

			this.ContentSize = new Size(this.LayerSize.Width * this.MapTileSize.Width, this.LayerSize.Height * this.MapTileSize.Height);
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Return the value for the specific property name.
		/// </summary>
		/// <param name="propertyName">Property name</param>
		/// <returns>Property value</returns>
		public string PropertyNamed(string propertyName)
		{
			return Properties[propertyName];
		}

		/// <summary>
		/// Creates the tiles.
		/// </summary>
		public void SetupTiles()
		{
			Tileset.ImageSize = Surface.ContentSize;

			for (int y = 0; y < LayerSize.Height; y++)
			{
				for (int x = 0; x < LayerSize.Width; x++)
				{
					int pos = x + y * LayerSize.Width;
					int gid = Tiles[pos];

					// gid == 0 --> empty tile
					if (gid != 0)
					{
						this.AddTileHelper(gid, new Point(x, y));

						minGId = Math.Min(minGId, gid);
						maxGId = Math.Max(maxGId, gid);
					}
				}
			}

			Debug.Assert(minGId >= Tileset.FirstGId && maxGId >= Tileset.FirstGId, "PKTmxLayer.SetupTiles: Only 1 tilset per layer is supported.");
		}

		/// <summary>
		/// Get the tile (CCSprite) at a given a tile coordinate.
		/// </summary>
		/// <param name="pos">Specified coordinate</param>
		/// <returns>Expected tile</returns>
		/// <remarks>The returned PKSprite will be already added to the PKTmxLayer. Don't add it again.</remarks>
		/// <remarks>The PKSprite can be treated like any other PKSprite: opacity, hue, etc.</remarks>
		public PKSprite GetTile(Point pos)
		{
			Debug.Assert(pos.X < LayerSize.Width && pos.Y < LayerSize.Height && pos.X >= 0 && pos.Y >= 0, "PKTmxLayer.GetTile: Invalid position.");
			Debug.Assert(Tiles != null, "PKTmxLayer.GetTile: The tiles map has been released.");

			PKSprite tile = null;
			int gid = this.GetTileGId(pos);

			// If GID == 0, then no tile is present.
			if (gid != 0)
			{
				int z = pos.X + pos.Y * LayerSize.Width;
				tile = this.GetChildByTag(z) as PKSprite;

				// Tile not created yet. Create it.
				if (tile == null)
				{
					Rectangle rect = Tileset.RectForGId(gid);
					tile = new PKSprite(Surface, rect);
					tile.Position = this.PositionAt(pos);
					tile.Opacity = opacity;
					base.AddChild(tile, pos.Y, z);
				}
			}

			return tile;
		}

		/// <summary>
		/// Get the tile gid at a given tile coordinate.
		/// </summary>
		/// <param name="pos">Specified coordinate</param>
		/// <returns>GId of expected tile</returns>
		/// <remarks>If it returns 0, it means that the tile is empty.</remarks>
		public int GetTileGId(Point pos)
		{
			Debug.Assert(pos.X < LayerSize.Width && pos.Y < LayerSize.Height && pos.X >= 0 && pos.Y >= 0, "PKTmxLayer.GetTileGId: Invalid position.");
			Debug.Assert(Tiles != null, "PKTmxLayer.GetTileGId: The tiles map has been released.");

			int z = pos.X + pos.Y * LayerSize.Width;
			return Tiles[z];
		}

		/// <summary>
		/// Sets the tile gid (gid = tile global id) at a given tile coordinate.
		/// </summary>
		/// <param name="gid">GId for target tile</param>
		/// <param name="pos">Specified coordinate</param>
		public void SetTileGId(int gid, Point pos)
		{
			Debug.Assert(pos.X < LayerSize.Width && pos.Y < LayerSize.Height && pos.X >= 0 && pos.Y >= 0, "PKTmxLayer.SetTileGId: Invalid position.");
			Debug.Assert(Tiles != null, "PKTmxLayer.SetTileGId: The tiles map has been released.");
			Debug.Assert(gid == 0 || gid >= Tileset.FirstGId, "PKTmxLayer.SetTileGId: Invalid GId.");

			int currentGId = GetTileGId(pos);
			if (currentGId != gid)
			{
				// Setting gid = 0 is equal to remove the tile.
				if (gid == 0)
				{
					this.RemoveTile(pos);
				}

				// Empty tile. Create a new one.
				else if (currentGId == 0)
				{
					this.AddTileHelper(gid, pos);
				}

				// Modifying an existing tile with a non-empty tile.
				else
				{
					this.UpdateTileHelper(gid, pos);
				}
			}
		}

		/// <summary>
		/// Removes a tile at given tile coordinate.
		/// </summary>
		/// <param name="pos">Specified coordinate</param>
		public void RemoveTile(Point pos)
		{
			Debug.Assert(pos.X < LayerSize.Width && pos.Y < LayerSize.Height && pos.X >= 0 && pos.Y >= 0, "PKTmxLayer.RemoveTile: Invalid position.");
			Debug.Assert(Tiles != null, "PKTmxLayer.RemoveTile: The tiles map has been released.");

			int gid = GetTileGId(pos);
			if (gid != 0)
			{
				int z = pos.X + pos.Y * LayerSize.Width;
				Tiles[z] = 0;

				PKNode node = this.GetChildByTag(z);
				if (node != null)
				{
					base.RemoveChild(node, true);
				}
			}
		}

		/// <summary>
		/// Get the position of a given tile coordinate.
		/// </summary>
		/// <param name="pos">Specified coordinate</param>
		/// <returns>Expected position</returns>
		public Point PositionAt(Point pos)
		{
			return new Point(pos.X * MapTileSize.Width, pos.Y * MapTileSize.Height);
		}

		/// <summary>
		/// Adds a node into the layer.
		/// </summary>
		/// <param name="node">Target node</param>
		/// <param name="zOrder">Target z order</param>
		public void AddNode(PKNode node, int zOrder)
		{
			base.AddChild(node, zOrder, PKNode.PKNodeInvalidTag);
		}

		public override void AddChild(PKNode child, int zOrder, int tag)
		{
			Debug.Assert(false, "PKTmxLayer.AddChild: Use SetTileGId / GetTile to add tile. Use AddNode to add child.");
		}

		public override void RemoveChild(PKNode child, bool needCleanup)
		{
			if (child == null)
			{
				return;
			}

			Debug.Assert(Children.Contains(child), "PKTmxLayer.RemoveChild: The tile does not belong to this TmxLayer");

			Tiles[child.Tag] = 0;
			base.RemoveChild(child, needCleanup);
		}
		#endregion

		#region Private Methods
		private PKSprite AddTileHelper(int gid, Point pos)
		{
			Rectangle rect = Tileset.RectForGId(gid);
			int z = pos.X + pos.Y * LayerSize.Width;
			PKSprite tile = new PKSprite(Surface, rect);
			tile.Position = this.PositionAt(pos);
			tile.Opacity = opacity;
			base.AddChild(tile, pos.Y, z);

			Tiles[z] = gid;
			return tile;
		}

		private PKSprite UpdateTileHelper(int gid, Point pos)
		{
			int z = pos.X + pos.Y * LayerSize.Width;
			PKSprite tile = this.GetChildByTag(z) as PKSprite;
			if (tile == null)
			{
				return AddTileHelper(gid, pos);
			}
			Rectangle rect = Tileset.RectForGId(gid);
			tile.SetDisplayFrame(new PKSpriteFrame(Surface, rect));
			tile.Position = this.PositionAt(pos);
			tile.Opacity = opacity;

			Tiles[z] = gid;
			return tile;
		}
		#endregion
	}
}
